package com.qsl.ssyx.acl.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.qsl.ssyx.acl.service.AdminRoleService;
import com.qsl.ssyx.acl.mapper.RoleMapper;
import com.qsl.ssyx.model.acl.AdminRole;
import com.qsl.ssyx.model.acl.Role;
import com.qsl.ssyx.acl.service.RoleService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.qsl.ssyx.vo.acl.RoleQueryVo;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * <p>
 * 角色 服务实现类
 * </p>
 *
 * @author 青衫泪
 * @since 2023-08-06
 */
@Slf4j
@Service
public class RoleServiceImpl extends ServiceImpl<RoleMapper, Role> implements RoleService {

    @Autowired
    private AdminRoleService adminRoleService;

    // 条件分页查询
    @Override
    public IPage<Role> selectPage(Page<Role> pageParam, RoleQueryVo roleQueryVo) {
        LambdaQueryWrapper<Role> lqw = new LambdaQueryWrapper();
        // 不为空
        if (!StringUtils.isEmpty(roleQueryVo.getRoleName())) {
            lqw.like(Role::getRoleName, roleQueryVo.getRoleName());
        }
        lqw.orderByDesc(Role::getId); // 倒序排序
        List<Role> roles = baseMapper.selectList(lqw);
        log.error("======2345=============>", roles);
        Page<Role> rolePage = baseMapper.selectPage(pageParam, lqw);
        return rolePage;
    }

    //    查询所有角色 和根据用户id查询已分配的角色
    @Override
    public Map<String, Object> getRoleAll(Integer adminId) {
        // 1.查询所有角色
        List<Role> allRoleList = baseMapper.selectList(null);
        // 2.根据用户id查询已分配的角色
        LambdaQueryWrapper<AdminRole> lqw = new LambdaQueryWrapper<>();
        lqw.eq(AdminRole::getAdminId, adminId);
        List<AdminRole> adminRoleList = adminRoleService.list(lqw);
        // 获取所有用id
        List<Long> roleIdsList = adminRoleList.stream().map(item -> item.getRoleId()).collect(Collectors.toList());
        // 存储用户配置角色
        List<Role> assignRoleList = new ArrayList<>();
        // 遍历角色列表，判断所有角色是否包含已分配角色id
        for (Role role : allRoleList) {
            if (roleIdsList.contains(role.getId())) {
                assignRoleList.add(role);
            }
        }

        Map<String, Object> map = new HashMap();
        map.put("allRolesList", allRoleList); // 所有角色
        map.put("assignRoles", assignRoleList); // 当前用户分配的角色
        System.out.println("==========>=>" + map);
        return map;
    }
}
